package wa.tools;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wa.application.AppException;
import wa.application.ApplicationImpl;
import wa.domain.Artifact;
import wa.domain.ArtifactType;
import wa.persist.ArtifactDAO;

public class CliImpl extends ApplicationImpl {

	EntityManagerFactory emf;
	EntityManager em;
	ArtifactDAO artifactDao;
	
	
	final Logger log = LoggerFactory.getLogger(CliImpl.class);
	
	public CliImpl(){
		// set basic appplication details
		setAppName("Weltanschauung CLI");
		setVersion("<maven snapshot>");
		setMinArgs(1);
		
		// construct expected parameters, order is important!
		addParameter("command");
		addParameter("commandParam");
		
		
		// add Flags, order is unimportant
		addFlag("-t");
		
		// set full help text
		String helpText = getFullHelpText()+
						  "\n -t strict test mode";
		setFullHelpText(helpText);
	}
	
	
	@Override
	public void preProcess() throws AppException {
		// read settings
		// wa.home ? -> alternativ test?
		
		// init persistence unit
		log.info("preProcess!");
		emf = Persistence.createEntityManagerFactory("derbyPU");
	    em = emf.createEntityManager();
	    artifactDao = new ArtifactDAO();
	    artifactDao.em = em;
	   
	}
	
	// wa -add "Software (2007)(Atari)"
	@Override
	public void process() throws AppException {
		// TODO Auto-generated method stub
		log.info("process...");
		String command = getParam("command");

		if (command.equalsIgnoreCase("add")) {
			log.info("adding: "+getParam("commandParam"));
			
			em.getTransaction().begin();
			Artifact artifact = new Artifact();
			artifact.setName("Name!");
			artifact.setType(ArtifactType.SOFTWARE);
			artifact = artifactDao.create(artifact);
			
			em.getTransaction().commit();
			log.info("Artifact:"+artifact);
		}
		setTerminationCode(0);
	}

	@Override
	public void postProcess() throws AppException {
		// TODO Auto-generated method stub
		log.info("postProcess");
	}

}
